var mainApp = angular.module("mainApp");

mainApp.controller("resourceController", function($rootScope, $scope, $http) {
	var rm = $scope.rm = {
		resourceList : []
	}

	rm.query = function() {
		$http.post("system/resource/list.do").success(function(data) {
			var res = {
				resourceList : data.reslist
			}
			rm.resourceList = [];
			rm.toTree(res, 0);
		})
	}

	rm.query();

	rm.toTree = function(res, depth) {
		depth++;
		angular.forEach(res.resourceList, function(it) {
			it.depth = depth;
			if (depth > 3) {
				res.isClosed = it.parIsClosed = true;
			}
			rm.resourceList.push(it);
			rm.toTree(it, depth);
		})
	}

	rm.resSwith = function(res) {
		angular.forEach(rm.resourceList, function(it) {
			if (res.id == it.parentid) {
				it.parIsClosed = res.isClosed;
				it.isClosed = res.isClosed;
				rm.resSwith(it);
			}
		})
	};

	rm.del = function(res) {
		$rootScope.confirm("该操作无法回滚，确认删除？", function() {
			$http.post("system/resource/del.do", {
				id : res.id
			}).success(function(data) {
				$("#delete").modal("hide");
				rm.query();
			})
		})
	}

	rm.add = function(res) {
		rm.title = "菜单添加";
		rm.currentRes = res;
		rm.isEdit = false;
		rm.resource = [];
	}

	rm.edit = function(res) {
		rm.title = "菜单修改";
		rm.resource = angular.copy(res);
		rm.isEdit = true;
	}

	rm.addOrEdit = function(form) {
		rm.showError = true;
		form.$setDirty();
		if (form.$valid) {
			if (!rm.isEdit) {
				rm.resource.parentid = rm.currentRes.id;
			}
			rm.resource.resourceList = [];
			$http.post("system/resource/addOrEdit.do", rm.resource).success(
					function(data) {
						rm.showMessage = true;
						rm.result = data.result;
						if (data.result == 0) {
							rm.message = '操作失败！';
						} else {
							rm.message = '操作成功!';
						}
						form.$setPristine();
					})
			rm.showError = false;
		}
	}

	$("#resourceDetail").on("hidden.bs.modal", function() {
		rm.resource = [];
		rm.currentRes = [];
		rm.showMessage = false;
		rm.query();
	})
})